/**
 * 社区模块Vuex状态管理
 * @module store/modules/community
 * @author 互成一家
 * @description 社区相关的状态管理
 */
import * as communityApi from '../../api/community';

// 初始状态
const state = {
  // 标签列表
  tagList: [],
  // 当前选中的标签
  currentTag: 'all',
  // 动态列表
  postList: [],
  // 动态详情
  currentPost: null,
  // 评论列表
  commentList: [],
  // 用户信息
  userInfo: null,
  // 用户动态列表
  userPosts: [],
  // 分页信息
  pagination: {
    page: 1,
    pageSize: 10,
    total: 0,
    hasMore: true
  },
  // 加载状态
  loading: {
    tagList: false,
    postList: false,
    postDetail: false,
    commentList: false,
    userInfo: false,
    userPosts: false
  }
};

// getters
const getters = {
  // 获取标签列表
  tagList: state => state.tagList,
  // 获取当前选中的标签
  currentTag: state => state.currentTag,
  // 获取动态列表
  postList: state => state.postList,
  // 获取当前动态详情
  currentPost: state => state.currentPost,
  // 获取评论列表
  commentList: state => state.commentList,
  // 获取用户信息
  userInfo: state => state.userInfo,
  // 获取用户动态列表
  userPosts: state => state.userPosts,
  // 获取分页信息
  pagination: state => state.pagination,
  // 获取加载状态
  loading: state => state.loading
};

// mutations
const mutations = {
  // 设置标签列表
  SET_TAG_LIST(state, tagList) {
    state.tagList = tagList;
  },
  // 设置当前选中的标签
  SET_CURRENT_TAG(state, tag) {
    state.currentTag = tag;
  },
  // 设置动态列表
  SET_POST_LIST(state, postList) {
    state.postList = postList;
  },
  // 添加动态列表（加载更多）
  ADD_POST_LIST(state, postList) {
    state.postList = [...state.postList, ...postList];
  },
  // 设置当前动态详情
  SET_CURRENT_POST(state, post) {
    state.currentPost = post;
  },
  // 更新动态点赞状态
  UPDATE_POST_LIKE(state, { postId, isLike }) {
    // 更新列表中的动态
    const post = state.postList.find(p => p.id === Number(postId));
    if (post) {
      post.isLiked = isLike;
      post.likesCount = isLike ? post.likesCount + 1 : Math.max(0, post.likesCount - 1);
    }
    
    // 更新当前动态
    if (state.currentPost && state.currentPost.id === Number(postId)) {
      state.currentPost.isLiked = isLike;
      state.currentPost.likesCount = isLike ? state.currentPost.likesCount + 1 : Math.max(0, state.currentPost.likesCount - 1);
    }
  },
  // 设置评论列表
  SET_COMMENT_LIST(state, commentList) {
    state.commentList = commentList;
  },
  // 添加评论列表（加载更多）
  ADD_COMMENT_LIST(state, commentList) {
    state.commentList = [...state.commentList, ...commentList];
  },
  // 添加评论
  ADD_COMMENT(state, comment) {
    state.commentList.unshift(comment);
    
    // 更新动态评论数
    if (state.currentPost && state.currentPost.id === comment.postId) {
      state.currentPost.commentsCount += 1;
    }
    
    const post = state.postList.find(p => p.id === comment.postId);
    if (post) {
      post.commentsCount += 1;
    }
  },
  // 设置用户信息
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  // 更新用户关注状态
  UPDATE_USER_FOLLOW(state, { userId, isFollow }) {
    if (state.userInfo && state.userInfo.id === Number(userId)) {
      state.userInfo.isFollowed = isFollow;
      state.userInfo.followersCount = isFollow ? state.userInfo.followersCount + 1 : Math.max(0, state.userInfo.followersCount - 1);
    }
  },
  // 设置用户动态列表
  SET_USER_POSTS(state, posts) {
    state.userPosts = posts;
  },
  // 添加用户动态列表（加载更多）
  ADD_USER_POSTS(state, posts) {
    state.userPosts = [...state.userPosts, ...posts];
  },
  // 设置分页信息
  SET_PAGINATION(state, pagination) {
    state.pagination = { ...state.pagination, ...pagination };
  },
  // 设置加载状态
  SET_LOADING(state, { type, status }) {
    state.loading = { ...state.loading, [type]: status };
  },
  // 重置状态
  RESET_STATE(state, type) {
    switch (type) {
      case 'postList':
        state.postList = [];
        state.pagination = {
          page: 1,
          pageSize: 10,
          total: 0,
          hasMore: true
        };
        break;
      case 'commentList':
        state.commentList = [];
        state.pagination = {
          page: 1,
          pageSize: 10,
          total: 0,
          hasMore: true
        };
        break;
      case 'userPosts':
        state.userPosts = [];
        state.pagination = {
          page: 1,
          pageSize: 10,
          total: 0,
          hasMore: true
        };
        break;
      case 'all':
        Object.assign(state, {
          tagList: [],
          currentTag: 'all',
          postList: [],
          currentPost: null,
          commentList: [],
          userInfo: null,
          userPosts: [],
          pagination: {
            page: 1,
            pageSize: 10,
            total: 0,
            hasMore: true
          },
          loading: {
            tagList: false,
            postList: false,
            postDetail: false,
            commentList: false,
            userInfo: false,
            userPosts: false
          }
        });
        break;
      default:
        break;
    }
  }
};

// actions
const actions = {
  /**
   * 获取标签列表
   * @async
   * @function fetchTagList
   * @param {Object} context - Vuex上下文
   * @returns {Promise<Array>} 标签列表
   */
  async fetchTagList({ commit }) {
    commit('SET_LOADING', { type: 'tagList', status: true });
    try {
      const res = await communityApi.getTagList();
      console.log('获取标签列表结果:', res);
      if (res && res.code === 200) {
        commit('SET_TAG_LIST', res.data);
        return res.data;
      }
      return [];
    } catch (error) {
      console.error('获取标签列表失败', error);
      return [];
    } finally {
      commit('SET_LOADING', { type: 'tagList', status: false });
    }
  },
  
  /**
   * 获取动态列表
   * @async
   * @function fetchPostList
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 查询参数
   * @param {String} [params.tag] - 标签ID
   * @param {Boolean} [params.followed] - 是否只看关注的用户
   * @param {Boolean} [params.refresh=false] - 是否刷新
   * @returns {Promise<Object>} 动态列表和分页信息
   */
  async fetchPostList({ commit, state }, params = {}) {
    const { tag, followed, refresh = false } = params;
    
    // 设置当前标签
    if (tag) {
      commit('SET_CURRENT_TAG', tag);
    }
    
    // 如果是刷新，重置状态
    if (refresh) {
      commit('RESET_STATE', 'postList');
    }
    
    // 如果没有更多数据，直接返回
    if (!refresh && !state.pagination.hasMore) {
      return { list: state.postList, pagination: state.pagination };
    }
    
    commit('SET_LOADING', { type: 'postList', status: true });
    
    try {
      const res = await communityApi.getPostList({
        tag: tag || state.currentTag,
        followed,
        page: state.pagination.page,
        pageSize: state.pagination.pageSize
      });
      
      console.log('获取动态列表结果:', res);
      
      if (res && res.code === 200) {
        const { list, pagination } = res.data;
        
        // 直接设置动态列表，先不处理分页
        if (refresh) {
          commit('SET_POST_LIST', list);
        } else {
          commit('ADD_POST_LIST', list);
        }
        
        // 设置分页信息
        if (pagination) {
          commit('SET_PAGINATION', {
            page: pagination.page || 1,
            pageSize: pagination.pageSize || 10,
            total: pagination.total || list.length,
            hasMore: pagination.hasMore || false
          });
          
          // 更新页码
          if (pagination.hasMore) {
            commit('SET_PAGINATION', { page: (pagination.page || 1) + 1 });
          }
        }
        
        return { list, pagination: pagination || { hasMore: false } };
      }
      
      return { list: [], pagination: { hasMore: false } };
    } catch (error) {
      console.error('获取动态列表失败', error);
      return { list: [], pagination: { hasMore: false } };
    } finally {
      commit('SET_LOADING', { type: 'postList', status: false });
    }
  },
  
  /**
   * 获取动态详情
   * @async
   * @function fetchPostDetail
   * @param {Object} context - Vuex上下文
   * @param {Number|String} postId - 动态ID
   * @returns {Promise<Object>} 动态详情
   */
  async fetchPostDetail({ commit }, postId) {
    commit('SET_LOADING', { type: 'postDetail', status: true });
    
    try {
      const res = await communityApi.getPostDetail(postId);
      
      if (res.code === 200) {
        commit('SET_CURRENT_POST', res.data);
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('获取动态详情失败', error);
      return null;
    } finally {
      commit('SET_LOADING', { type: 'postDetail', status: false });
    }
  },
  
  /**
   * 获取评论列表
   * @async
   * @function fetchCommentList
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 查询参数
   * @param {Number|String} params.postId - 动态ID
   * @param {Boolean} [params.refresh=false] - 是否刷新
   * @returns {Promise<Object>} 评论列表和分页信息
   */
  async fetchCommentList({ commit, state }, params = {}) {
    const { postId, refresh = false } = params;
    
    // 如果是刷新，重置状态
    if (refresh) {
      commit('RESET_STATE', 'commentList');
    }
    
    // 如果没有更多数据，直接返回
    if (!refresh && !state.pagination.hasMore) {
      return { list: state.commentList, pagination: state.pagination };
    }
    
    commit('SET_LOADING', { type: 'commentList', status: true });
    
    try {
      const res = await communityApi.getCommentList({
        postId,
        page: state.pagination.page,
        pageSize: state.pagination.pageSize
      });
      
      if (res.code === 200) {
        const { list, pagination } = res.data;
        
        // 设置分页信息
        commit('SET_PAGINATION', {
          page: pagination.page,
          pageSize: pagination.pageSize,
          total: pagination.total,
          hasMore: pagination.hasMore
        });
        
        // 设置评论列表
        if (refresh) {
          commit('SET_COMMENT_LIST', list);
        } else {
          commit('ADD_COMMENT_LIST', list);
        }
        
        // 更新页码
        if (pagination.hasMore) {
          commit('SET_PAGINATION', { page: pagination.page + 1 });
        }
        
        return { list, pagination };
      }
      
      return { list: [], pagination: { hasMore: false } };
    } catch (error) {
      console.error('获取评论列表失败', error);
      return { list: [], pagination: { hasMore: false } };
    } finally {
      commit('SET_LOADING', { type: 'commentList', status: false });
    }
  },
  
  /**
   * 获取用户信息
   * @async
   * @function fetchUserInfo
   * @param {Object} context - Vuex上下文
   * @param {Number|String} userId - 用户ID
   * @returns {Promise<Object>} 用户信息
   */
  async fetchUserInfo({ commit }, userId) {
    commit('SET_LOADING', { type: 'userInfo', status: true });
    
    try {
      const res = await communityApi.getUserInfo(userId);
      
      if (res.code === 200) {
        commit('SET_USER_INFO', res.data);
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('获取用户信息失败', error);
      return null;
    } finally {
      commit('SET_LOADING', { type: 'userInfo', status: false });
    }
  },
  
  /**
   * 获取用户动态列表
   * @async
   * @function fetchUserPosts
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 查询参数
   * @param {Number|String} params.userId - 用户ID
   * @param {Boolean} [params.refresh=false] - 是否刷新
   * @returns {Promise<Object>} 用户动态列表和分页信息
   */
  async fetchUserPosts({ commit, state }, params = {}) {
    const { userId, refresh = false } = params;
    
    // 如果是刷新，重置状态
    if (refresh) {
      commit('RESET_STATE', 'userPosts');
    }
    
    // 如果没有更多数据，直接返回
    if (!refresh && !state.pagination.hasMore) {
      return { list: state.userPosts, pagination: state.pagination };
    }
    
    commit('SET_LOADING', { type: 'userPosts', status: true });
    
    try {
      const res = await communityApi.getUserPosts({
        userId,
        page: state.pagination.page,
        pageSize: state.pagination.pageSize
      });
      
      if (res.code === 200) {
        const { list, pagination } = res.data;
        
        // 设置分页信息
        commit('SET_PAGINATION', {
          page: pagination.page,
          pageSize: pagination.pageSize,
          total: pagination.total,
          hasMore: pagination.hasMore
        });
        
        // 设置用户动态列表
        if (refresh) {
          commit('SET_USER_POSTS', list);
        } else {
          commit('ADD_USER_POSTS', list);
        }
        
        // 更新页码
        if (pagination.hasMore) {
          commit('SET_PAGINATION', { page: pagination.page + 1 });
        }
        
        return { list, pagination };
      }
      
      return { list: [], pagination: { hasMore: false } };
    } catch (error) {
      console.error('获取用户动态列表失败', error);
      return { list: [], pagination: { hasMore: false } };
    } finally {
      commit('SET_LOADING', { type: 'userPosts', status: false });
    }
  },
  
  /**
   * 发布动态
   * @async
   * @function createPost
   * @param {Object} context - Vuex上下文
   * @param {Object} postData - 动态数据
   * @returns {Promise<Object>} 发布结果
   */
  async createPost({ dispatch }, postData) {
    try {
      const res = await communityApi.createPost(postData);
      
      if (res.code === 200) {
        // 刷新动态列表
        await dispatch('fetchPostList', { refresh: true });
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('发布动态失败', error);
      return null;
    }
  },
  
  /**
   * 删除动态
   * @async
   * @function deletePost
   * @param {Object} context - Vuex上下文
   * @param {Number|String} postId - 动态ID
   * @returns {Promise<Object>} 删除结果
   */
  async deletePost({ dispatch }, postId) {
    try {
      const res = await communityApi.deletePost(postId);
      
      if (res.code === 200) {
        // 刷新动态列表
        await dispatch('fetchPostList', { refresh: true });
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('删除动态失败', error);
      return null;
    }
  },
  
  /**
   * 点赞/取消点赞动态
   * @async
   * @function likePost
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 参数
   * @param {Number|String} params.postId - 动态ID
   * @param {Boolean} params.isLike - 是否点赞
   * @returns {Promise<Object>} 操作结果
   */
  async likePost({ commit }, params) {
    const { postId, isLike } = params;
    
    try {
      const res = await communityApi.likePost(params);
      
      if (res.code === 200) {
        // 更新动态点赞状态
        commit('UPDATE_POST_LIKE', { postId, isLike });
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('点赞操作失败', error);
      return null;
    }
  },
  
  /**
   * 发表评论
   * @async
   * @function createComment
   * @param {Object} context - Vuex上下文
   * @param {Object} commentData - 评论数据
   * @returns {Promise<Object>} 发表结果
   */
  async createComment({ commit }, commentData) {
    try {
      const res = await communityApi.createComment(commentData);
      
      if (res.code === 200) {
        // 添加评论
        commit('ADD_COMMENT', res.data.comment);
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('发表评论失败', error);
      return null;
    }
  },
  
  /**
   * 申请添加好友
   * @async
   * @function addFriend
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 参数
   * @returns {Promise<Object>} 申请结果
   */
  async addFriend(_, params) {
    try {
      const res = await communityApi.addFriend(params);
      
      if (res.code === 200) {
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('申请添加好友失败', error);
      return null;
    }
  },
  
  /**
   * 关注/取消关注用户
   * @async
   * @function followUser
   * @param {Object} context - Vuex上下文
   * @param {Object} params - 参数
   * @param {Number|String} params.userId - 用户ID
   * @param {Boolean} params.isFollow - 是否关注
   * @returns {Promise<Object>} 操作结果
   */
  async followUser({ commit }, params) {
    const { userId, isFollow } = params;
    
    try {
      const res = await communityApi.followUser(params);
      
      if (res.code === 200) {
        // 更新用户关注状态
        commit('UPDATE_USER_FOLLOW', { userId, isFollow });
        return res.data;
      }
      
      return null;
    } catch (error) {
      console.error('关注操作失败', error);
      return null;
    }
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
